package com.uzai.console.service.wechatwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.KefuSendMsgEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.enums.MessageTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wxgroup.*;
import com.uzai.console.dto.wechatwork.wxq.rule.*;
import com.uzai.console.dto.wechatwork.wxq.welcome.*;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.*;
import com.uzai.console.dto.wechatwork.wxq.wxgroupmenber.WxWorkGroupMemberKickDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsWorkWxContacts;
import com.uzai.console.entity.es.EsWorkWxGroupInfo;
import com.uzai.console.enums.DeviceProductEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.wechatwork.WxWorkGroupMemberService;
import com.uzai.console.service.wechatwork.WxWorkGroupService;
import com.uzai.console.vo.wechatwork.wxq.managerfunc.WxqWorkGroupManagerFuncVo;
import com.uzai.console.vo.wechatwork.wxq.rule.WxWorkGroupRuleVo;
import com.uzai.console.vo.wechatwork.wxq.welcome.WxWorkGroupWelcomeVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroup.WxWorkGroupInfoVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroup.WxWorkGroupQrcodeVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 企业微信-微信群
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxWorkGroupServiceImpl implements WxWorkGroupService {

    Logger logger = LoggerFactory.getLogger(WxWorkGroupServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private WxqWorkManagePlanMapper wxqWorkManagePlanMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private WxqWorkGroupWelcomeMapper wxqWorkGroupWelcomeMapper;
    @Autowired
    private WxqWorkGroupRuleMapper wxqWorkGroupRuleMapper;
    @Autowired
    private WxWorkGroupMemberService wxWorkGroupMemberService;
    @Autowired
    private WxqWorkGroupManagerFuncMapper wxqWorkGroupManagerFuncMapper;


    /**
     * 查询微信群列表
     *
     * @param wxWorkGroupQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<WxWorkGroupInfoVo> findWxWorkGroupList(WxWorkGroupQuery wxWorkGroupQuery) {
        //新建返回到页面的LIST对象
        List<WxWorkGroupInfoVo> wxWorkGroupInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxWorkGroupInfoVo> page = new Page<>();
        wxWorkGroupQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_deviceList = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_keyword = QueryBuilders.boolQuery();
        //BoolQueryBuilder boolQuery_or_groupIdExcludeList = QueryBuilders.boolQuery();
        //BoolQueryBuilder boolQuery_or_wxidExcludeList = QueryBuilders.boolQuery();


        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxWorkGroupQuery.getMerId())));

        //微信群id
        if(StringUtils.isNotBlank(wxWorkGroupQuery.getGroupId())){
            boolQuery_and.must(QueryBuilders.termQuery("groupId", wxWorkGroupQuery.getGroupId()));
        }

        //微信群昵称
        if(StringUtils.isNotBlank(wxWorkGroupQuery.getNickName())){
            boolQuery_or_keyword.should(QueryBuilders.termQuery("groupId",wxWorkGroupQuery.getNickName()));
            //boolQuery_and.must(QueryBuilders.matchQuery("nickName", wxWorkGroupQuery.getNickName()));
            //支持分词
            //boolQuery_or_keyword.should(QueryBuilders.matchQuery("nickName", wxWorkGroupQuery.getNickName()));
            //boolQuery_or_keyword.should(QueryBuilders.matchQuery("remark", wxWorkGroupQuery.getNickName()));
            //支持英文和字母
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("nickName.keyword", "*" + wxWorkGroupQuery.getNickName() +"*"));
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("remark.keyword", "*" + wxWorkGroupQuery.getNickName() + "*"));
        }

        //机器人唯一ID
        if(wxWorkGroupQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId", wxWorkGroupQuery.getDeviceUniqueId()));
        }

        //开启过滤未配置管理方案的群
        if(Tools.getInteger(wxWorkGroupQuery.getManagePlanIdFlag()).intValue() == 1){
            boolQuery_and.must(QueryBuilders.rangeQuery("managePlanId").gte(0));
        }

        //管理方案方案id
        if(wxWorkGroupQuery.getManagePlanId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("managePlanId", wxWorkGroupQuery.getManagePlanId()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxWorkGroupQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //机器人唯一id列表
        List<Long> deviceUniqueIdList = wxWorkGroupQuery.getDeviceUniqueIdList();
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : deviceUniqueIdList) {
                boolQuery_or_deviceList.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //排除群id(id主键)
        List<String> groupIdExcludeList = wxWorkGroupQuery.getGroupIdExcludeList();
        if(groupIdExcludeList != null && groupIdExcludeList.size() > 0){
            for (String groupId : groupIdExcludeList) {
                boolQuery_and.mustNot(QueryBuilders.termQuery("id.keyword", groupId));
            }
        }

        //排除群wxid
        List<String> wxidExcludeList = wxWorkGroupQuery.getWxidExcludeList();
        if(wxidExcludeList != null && wxidExcludeList.size() > 0){
            for (String wxid : wxidExcludeList) {
                boolQuery_and.mustNot(QueryBuilders.termQuery("groupId.keyword", wxid));
            }
        }

        //关键词搜索-群昵称
        if(StringUtils.isNotBlank(wxWorkGroupQuery.getKeyword())){
            boolQuery_or_keyword.should(QueryBuilders.termQuery("groupId",wxWorkGroupQuery.getKeyword()));
            //支持分词
            //boolQuery_or_keyword.should(QueryBuilders.matchQuery("nickName", wxWorkGroupQuery.getKeyword()));
            //boolQuery_or_keyword.should(QueryBuilders.matchQuery("remark", wxWorkGroupQuery.getKeyword()));
            //支付英文和数字
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("nickName.keyword", "*" + wxWorkGroupQuery.getKeyword() +"*"));
            boolQuery_or_keyword.should(QueryBuilders.wildcardQuery("remark.keyword", "*" + wxWorkGroupQuery.getKeyword() + "*"));
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or).must(boolQuery_or_deviceList).must(boolQuery_or_keyword));

        //logger.info(searchSourceBuilder.toString());

        //searchSourceBuilder.query(boolQuery_and.must(boolQuery_or).must(boolQuery_or_deviceList).mustNot(boolQuery_or_groupIdExcludeList).mustNot(boolQuery_or_wxidExcludeList));

        //判断根据群wxid去重
        //去重计数字段
        String distinctCount = "distinctCount";
        if(Tools.getInteger(wxWorkGroupQuery.getWxidDistinctFlag()).intValue() == 1){//去重
            //需要去重的字段名
            CollapseBuilder collapseBuilder = new CollapseBuilder("groupId");//针对群wxid字段去重
            //查询去重后的结果数量计数（前者参数为计数自定义名字，后者参数为指定需要计数的字段）
            CardinalityAggregationBuilder aggregationBuilder = AggregationBuilders.cardinality(distinctCount).field("groupId");
            searchSourceBuilder.collapse(collapseBuilder);
            searchSourceBuilder.aggregation(aggregationBuilder);
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupQuery.getMerId());

        ESResult esResult = null;

        if(Tools.getInteger(wxWorkGroupQuery.getWxidDistinctFlag()).intValue() == 1) {//去重
            esResult = elasticsearchUtilGroupMsg.distinctSearchListData(uzai_workwx_group_info, searchSourceBuilder, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, wxWorkGroupQuery.getMerId(), distinctCount);
        }else{
            esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_info, searchSourceBuilder, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, wxWorkGroupQuery.getMerId());
        }

        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxWorkGroupInfoVo wxWorkGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxWorkGroupInfoVo.class);
                //机器人信息
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxWorkGroupInfoVo.getDeviceUniqueId(), wxWorkGroupInfoVo.getMerId());
                if(deviceWxworkInfo != null){
                    wxWorkGroupInfoVo.setDeviceName(deviceWxworkInfo.getDeviceName());
                    wxWorkGroupInfoVo.setDeviceRemark(deviceWxworkInfo.getDeviceRemark());
                }

                //管理方案信息
                if(wxWorkGroupInfoVo.getManagePlanId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(wxWorkGroupInfoVo.getManagePlanId(), wxWorkGroupInfoVo.getMerId());
                    if(configPlan != null){
                        wxWorkGroupInfoVo.setManagePlanName(configPlan.getName());
                        wxWorkGroupInfoVo.setManageConfigFlag(1); //配置了管理方案
                        //查询配置方案的功能设置
                        if(configPlan.getGroupBasesetId() != null){
                            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getGroupBasesetId(), configPlan.getMerId());
                            if(sysPlugin != null){
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                if(jsonObject != null){
                                    //是否开启返利功能
                                    wxWorkGroupInfoVo.setFlSwitch(Tools.getInteger(jsonObject.getInteger("flSwitch")));
                                    //是否开启免单功能
                                    wxWorkGroupInfoVo.setMdSwitch(Tools.getInteger(jsonObject.getInteger("mdSwitch")));
                                    //是否开启发单功能
                                    wxWorkGroupInfoVo.setFdSwitch(Tools.getInteger(jsonObject.getInteger("fdSwitch")));
                                    //是否开启群内提现功能
                                    wxWorkGroupInfoVo.setTxSwitch(Tools.getInteger(jsonObject.getInteger("txSwitch")));
                                }
                            }
                        }
                    }
                }

                //判断是否购买了发单功能
                int now = DateUtil.getNowTime();
                DeviceAuth deviceAuth_fd = deviceAuthMapper.selectByDeviceIdAndProductCode(wxWorkGroupInfoVo.getDeviceId(), DeviceProductEnum.FD.getValue());
                if(deviceAuth_fd != null){
                    if(deviceAuth_fd.getExpireTime() > now){
                        wxWorkGroupInfoVo.setFdBuyFlag(1);
                    }
                }

                //怕段是否购买了托功能
                DeviceAuth deviceAuth_tuo = deviceAuthMapper.selectByDeviceIdAndProductCode(wxWorkGroupInfoVo.getDeviceId(), DeviceProductEnum.TUO.getValue());
                if(deviceAuth_tuo != null){
                    if(deviceAuth_tuo.getExpireTime() > now){
                        wxWorkGroupInfoVo.setTuoBuyFlag(1);
                    }
                }

                //是否有群二维码
                String wxWorkGroupQrcodeKey = String.format(RedisCacheKeyEnum.WXWORK_GROUP_QRCODE.getKey(), wxWorkGroupInfoVo.getId());
                Object object = redisTemplate.opsForValue().get(wxWorkGroupQrcodeKey);
                if(object != null){
                    wxWorkGroupInfoVo.setQrcode(object.toString());
                }

                //从redis中获取群成员个数
                String key = String.format(RedisCacheKeyEnum.WX_GROUP_MEMBER_COUNT.getKey(), wxWorkGroupInfoVo.getGroupId());
                Object wx_group_member_count = redisTemplate.opsForValue().get(key);
                if(wx_group_member_count != null){
                    wxWorkGroupInfoVo.setMemberTotal((Integer)wx_group_member_count);
                }

                wxWorkGroupInfoVoList.add(wxWorkGroupInfoVo);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxWorkGroupInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }


    /**
     * 查询微信群详情
     *
     * @param wxWorkGroupIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public WxWorkGroupInfoVo findWxWorkGroupInfo(WxWorkGroupIdDto wxWorkGroupIdDto){
        WxWorkGroupInfoVo wxWorkGroupInfoVo = new WxWorkGroupInfoVo();
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());
        Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        if(dataMap != null) { //存在群ES中
            wxWorkGroupInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxWorkGroupInfoVo.class);
        }
        return wxWorkGroupInfoVo;
    }

    /**
     * 查询微信群列表-根据已经配置了管理方案来查询
     *
     * @param wxqWorkGroupManagePlanQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
//    public Page<WxWorkGroupInfoVo> findWxqWorkGroupManagePlanList(WxqWorkGroupManagePlanQuery wxqWorkGroupManagePlanQuery){
//
//        //查询
//        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxqWorkGroupManagePlanQuery.getMerId());
//
//        //新建返回到页面的LIST对象
//        List<WxWorkGroupInfoVo> wxWorkGroupInfoVoList = new ArrayList<>();
//        //执行分页查询对象
//        Page<WxqWorkGroupManagePlan> page = new Page<>();
//        wxqWorkGroupManagePlanQuery.convert(page);
//
//        List<WxqWorkGroupManagePlan> wxqWorkGroupManagePlanList = wxqWorkGroupManagePlanMapper.findByList(page, wxqWorkGroupManagePlanQuery);
//
//        if(wxqWorkGroupManagePlanList != null && wxqWorkGroupManagePlanList.size() > 0) {
//            for (WxqWorkGroupManagePlan wxqWorkGroupManagePlan : wxqWorkGroupManagePlanList) {
//                String id = wxqWorkGroupManagePlan.getMerId() + "_" + wxqWorkGroupManagePlan.getDeviceId() + "_" + wxqWorkGroupManagePlan.getGroupId();
//                Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, id, null);
//                if(dataMap != null){ //存在群ES中
//                    WxWorkGroupInfoVo wxWorkGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxWorkGroupInfoVo.class);
//                    if(wxWorkGroupInfoVo != null) {
//                        //机器人信息
//                        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxWorkGroupInfoVo.getDeviceUniqueId(), wxWorkGroupInfoVo.getMerId());
//                        if (deviceWxworkInfo != null) {
//                            wxWorkGroupInfoVo.setDeviceName(deviceWxworkInfo.getDeviceName());
//                            wxWorkGroupInfoVo.setDeviceRemark(deviceWxworkInfo.getDeviceRemark());
//                        }
//
//                        //配置方案信息
//                        if(wxqWorkGroupManagePlan.getManagePlanId() != null) {
//                            ConfigPlan configPlan = configPlanMapper.selectById(wxqWorkGroupManagePlan.getManagePlanId(), wxqWorkGroupManagePlan.getMerId());
//                            if(configPlan != null){
//                                wxWorkGroupInfoVo.setManagePlanId(wxqWorkGroupManagePlan.getManagePlanId());
//                                wxWorkGroupInfoVo.setManagePlanName(configPlan.getName());
//                            }
//                        }
//
//                        //是否有群二维码
//                        String wxWorkGroupQrcodeKey = String.format(RedisCacheKeyEnum.WXWORK_GROUP_QRCODE.getKey(), wxWorkGroupInfoVo.getId());
//                        Object object = redisTemplate.opsForValue().get(wxWorkGroupQrcodeKey);
//                        if(object != null){
//                            wxWorkGroupInfoVo.setQrcode(object.toString());
//                        }
//                    }
//                    wxWorkGroupInfoVoList.add(wxWorkGroupInfoVo);
//                }else{ //不存在，则表示该群不存在，则需要自动清理该管理方案微信群
//                    wxqWorkGroupManagePlanMapper.deleteById(wxqWorkGroupManagePlan.getId(), wxqWorkGroupManagePlan.getMerId());
//                    //删除缓存中的微信群管理方案key
//                    String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), wxqWorkGroupManagePlan.getMerId(), wxqWorkGroupManagePlan.getDeviceId(), wxqWorkGroupManagePlan.getGroupId());
//                    redisTemplate.delete(redisKey_wxgroup_manageplan);
//                }
//            }
//        }
//
//        //返回页面的page
//        //执行分页查询对象
//        Page<WxWorkGroupInfoVo> pageResult = new Page<>();
//        wxqWorkGroupManagePlanQuery.convert(pageResult);
//        pageResult.setTotal(page.getTotal());
//        pageResult.setRecords(wxWorkGroupInfoVoList);
//        return pageResult;
//    }

    /**
     * 退群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public void quitWxWorkGroup(WxWorkGroupIdDto wxWorkGroupIdDto){

        if(wxWorkGroupIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }
        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());
        //查询
        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxWorkGroupIdDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo != null){
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupIdDto.getMerId());
            if(deviceWxworkInfo != null){
                //发送退群指令MQ消息
                MsgDto<QuitGroupDto> msgDto = new MsgDto<>();
                QuitGroupDto quitGroupDto = new QuitGroupDto();
                quitGroupDto.setGroupId(esWorkWxGroupInfo.getGroupId());
                quitGroupDto.setDelay(Tools.getInteger(wxWorkGroupIdDto.getDelay()));
                msgDto.setContent(quitGroupDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
                msgDto.setMerId(wxWorkGroupIdDto.getMerId());
                msgDto.setMsgType(MessageFuncEnum.QUIT_GROUP.getValue());
                noticeMsgPushProducerService.quitWxGroup(msgDto);
            }

            //删除群
            elasticsearchUtilGroupMsg.deleteDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId());

            //判断是否配置了管理方案，如果配置了管理费方案，则需要删除管理方案关系
            if(esWorkWxGroupInfo.getManagePlanId() != null){
                //删除缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), esWorkWxGroupInfo.getMerId(), esWorkWxGroupInfo.getDeviceId(), esWorkWxGroupInfo.getGroupId());
                redisTemplate.delete(redisKey_wxgroup_manageplan);
            }

            //判断是否删除群成员-查询该群id是否存在，如果不存在，则需要删除群成员
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //运营商ID
            boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxWorkGroupIdDto.getMerId())));
            //微信群微信id
            boolQuery.must(QueryBuilders.termQuery("groupId", esWorkWxGroupInfo.getGroupId()));
            searchSourceBuilder.query(boolQuery);
            WxWorkGroupQuery wxWorkGroupQuery = new WxWorkGroupQuery();
            ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_workwx_group_info, searchSourceBuilder, wxWorkGroupQuery.getSize(), wxWorkGroupQuery.getFromIndex(), null, null, null, wxWorkGroupQuery.getMerId());
            if(esResult.getTotalHits() == 0){ //表示没有群了，则需要清除该群所有成员
                DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
                //清空所有的发送明细
                SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
                //运营商ID
                boolQuery_and.must(QueryBuilders.termQuery("merId", wxWorkGroupIdDto.getMerId()));
                //群微信id
                boolQuery_and.must(QueryBuilders.termQuery("groupWxid", esWorkWxGroupInfo.getGroupId()));
                searchSourceBuilder_del.query(boolQuery_and).size(100);
                deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
                elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_wx_group_member, deleteByQueryRequest);

            }else{ //只清除该群内该机器人成员自己
                String id = wxWorkGroupIdDto.getMerId() + "_" + esWorkWxGroupInfo.getGroupId() + "_" + esWorkWxGroupInfo.getDeviceId();
                elasticsearchUtilGroupMsg.deleteDataById(uzai_wx_group_member, id);
            }
        }
    }

    /**
     * 单个发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupSendMessageDto
     * @return null
     */
    public void sendMessage(WxWorkGroupSendMessageDto wxWorkGroupSendMessageDto){

        if(StringUtils.isBlank(wxWorkGroupSendMessageDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxWorkGroupSendMessageDto.getMessage())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupSendMessageDto.getMerId());

        //查询微信群
        Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupSendMessageDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if (esWorkWxGroupInfo != null) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupSendMessageDto.getMerId());
            if(deviceWxworkInfo != null){
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                noticeMsgDto.setBizUserId(esWorkWxGroupInfo.getGroupId());
                noticeMsgDto.setContent(wxWorkGroupSendMessageDto.getMessage());
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(esWorkWxGroupInfo.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
                msgDto.setMerId(wxWorkGroupSendMessageDto.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }
    }

    /**
     * 修改管理方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupUpdateManagePlanDto
     * @return null
     */
    public void updateManagePlan(WxWorkGroupUpdateManagePlanDto wxWorkGroupUpdateManagePlanDto){
        if(StringUtils.isBlank(wxWorkGroupUpdateManagePlanDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupUpdateManagePlanDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupUpdateManagePlanDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        int now = DateUtil.getNowTime();

        //缓存中的微信群管理方案key
        String redisKey_wxgroup_work_manageplan = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), esWorkWxGroupInfo.getMerId(), esWorkWxGroupInfo.getDeviceId(), esWorkWxGroupInfo.getGroupId());
        //如果管理方案为空，则表示清空管理方案
        if(wxWorkGroupUpdateManagePlanDto.getManagePlanId() == null){ //清除管理方案

            //清除ES
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("managePlanId", null); //修改配置方案
//            jsonObject.put("updateTime", now);
//            elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_workwx_group_info, esWorkWxGroupInfo.getId());

            esWorkWxGroupInfo.setManagePlanId(null);
            esWorkWxGroupInfo.setUpdateTime(now);
            elasticsearchUtilGroupMsg.addData(esWorkWxGroupInfo, uzai_workwx_group_info, esWorkWxGroupInfo.getId());

            //清除缓存
            redisTemplate.delete(redisKey_wxgroup_work_manageplan);

        } else {//修改管理方案
            //修改ES
            esWorkWxGroupInfo.setManagePlanId(wxWorkGroupUpdateManagePlanDto.getManagePlanId());
            esWorkWxGroupInfo.setUpdateTime(now);
            elasticsearchUtilGroupMsg.addData(esWorkWxGroupInfo, uzai_workwx_group_info, esWorkWxGroupInfo.getId());

            //修改缓存
            redisTemplate.opsForValue().set(redisKey_wxgroup_work_manageplan, wxWorkGroupUpdateManagePlanDto.getManagePlanId());
        }
    }

    /**
     * 批量修改管理方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupBatchUpdateManagePlanDto
     * @return null
     */
    public void batchUpdateManagePlan(WxWorkGroupBatchUpdateManagePlanDto wxWorkGroupBatchUpdateManagePlanDto){
        //微信群id列表
        List<String> idList = wxWorkGroupBatchUpdateManagePlanDto.getIdList();
        //管理方案
        Long managePlanId = wxWorkGroupBatchUpdateManagePlanDto.getManagePlanId();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }
        for(String id  : idList){
            try {
                WxWorkGroupUpdateManagePlanDto wxWorkGroupUpdateManagePlanDto = new WxWorkGroupUpdateManagePlanDto();
                BeanUtils.copyProperties(wxWorkGroupBatchUpdateManagePlanDto, wxWorkGroupUpdateManagePlanDto);
                wxWorkGroupUpdateManagePlanDto.setMerId(wxWorkGroupBatchUpdateManagePlanDto.getMerId());
                wxWorkGroupUpdateManagePlanDto.setId(id);
                wxWorkGroupUpdateManagePlanDto.setManagePlanId(managePlanId);
                updateManagePlan(wxWorkGroupUpdateManagePlanDto);
            }catch (Exception e){

            }
        }
    }

    /**
     * 单个刷新群成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public void refreshGroupMember(WxWorkGroupIdDto wxWorkGroupIdDto){
        if(StringUtils.isBlank(wxWorkGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupIdDto.getMerId());
        if(deviceWxworkInfo != null){
            //发送MQ消息
            //发送刷新成员列表指令MQ消息
            MsgDto<GetGroupMemberListDto> msgDto = new MsgDto<>();
            GetGroupMemberListDto getGroupMemberListDto = new GetGroupMemberListDto();
            getGroupMemberListDto.setGroupId(esWorkWxGroupInfo.getGroupId());
            msgDto.setContent(getGroupMemberListDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
            msgDto.setMerId(wxWorkGroupIdDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.GET_GROUP_MEMBER_LIST.getValue());
            noticeMsgPushProducerService.getGroupMemberList(msgDto);
        }
    }

    /**
     * 修改群名称
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupUpdateNicknameDto
     * @return null
     */
    public void updateWxWorkGroupNickName(WxWorkGroupUpdateNicknameDto wxWorkGroupUpdateNicknameDto){
        if(StringUtils.isBlank(wxWorkGroupUpdateNicknameDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxWorkGroupUpdateNicknameDto.getGroupName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群名称");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupUpdateNicknameDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupUpdateNicknameDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupUpdateNicknameDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用微服务更新群名称
        MsgDto<UpdateNicknameDto> msgDto = new MsgDto<>();
        UpdateNicknameDto updateNicknameDto = new UpdateNicknameDto();
        updateNicknameDto.setGroupId(esWorkWxGroupInfo.getGroupId());
        updateNicknameDto.setNewGroupName(wxWorkGroupUpdateNicknameDto.getGroupName());
        msgDto.setContent(updateNicknameDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
        msgDto.setMerId(wxWorkGroupUpdateNicknameDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SET_GROUP_NAME.getValue());
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.setGroupName(msgDto);
        logger.info("--调用修改企业微信群名称接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }

        //修改通讯录群昵称
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nickName", wxWorkGroupUpdateNicknameDto.getGroupName());
        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_workwx_group_info, wxWorkGroupUpdateNicknameDto.getId());

        //延迟1秒
        try {
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 创建群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupCreateDto
     * @return null
     */
    public void createWxWorkGroup(WxWorkGroupCreateDto wxWorkGroupCreateDto){
        if(wxWorkGroupCreateDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人唯一id");
        }

        if(StringUtils.isBlank(wxWorkGroupCreateDto.getGroupName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群昵称");
        }

        List<String> memberIdList = wxWorkGroupCreateDto.getMemberIdList();
        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员");
        }
        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }
        //成员id列表
        List<String> wxidList = new ArrayList<>();
        //查询通讯录
        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxWorkGroupCreateDto.getMerId());
        for (String memberId : memberIdList) {
           //查询该成员信息
            Map<String,Object> dataMp_contacts = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, memberId, null);
            EsWorkWxContacts esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_contacts)), EsWorkWxContacts.class);
            if(esWorkWxGroupMember != null){
                wxidList.add(esWorkWxGroupMember.getWxid());
            }
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxWorkGroupCreateDto.getDeviceUniqueId(), wxWorkGroupCreateDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
        }

        //调用微服务创建群
        MsgDto<CreateWxworkGroupDto> msgDto = new MsgDto<>();
        CreateWxworkGroupDto createWxworkGroupDto = new CreateWxworkGroupDto();
        createWxworkGroupDto.setGroupName(wxWorkGroupCreateDto.getGroupName());
        createWxworkGroupDto.setArrWxids(String.join(";", wxidList));
        msgDto.setContent(createWxworkGroupDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(wxWorkGroupCreateDto.getDeviceUniqueId());
        msgDto.setMerId(wxWorkGroupCreateDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CREATE_GROUP.getValue());

        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.createGroup(msgDto);
        logger.info("--调用创建企业微信群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 邀请入群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupInviteDto
     * @return null
     */
    public void inviteWxWorkGroup(WxWorkGroupInviteDto wxWorkGroupInviteDto){
        if(StringUtils.isBlank(wxWorkGroupInviteDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        List<String> memberIdList = wxWorkGroupInviteDto.getMemberIdList();
        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员");
        }
        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }
        //成员id列表
        List<String> wxidList = new ArrayList<>();
        //查询通讯录
        String uzai_workwx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_CONTACTS, wxWorkGroupInviteDto.getMerId());
        for (String memberId : memberIdList) {
            //查询该成员信息
            Map<String,Object> dataMp_contacts = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_contacts, memberId, null);
            EsWorkWxContacts esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_contacts)), EsWorkWxContacts.class);
            if(esWorkWxGroupMember != null){
                wxidList.add(esWorkWxGroupMember.getWxid());
            }
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupInviteDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupInviteDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupInviteDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用微服务邀请入群
        MsgDto<InviteWxworkGroupDto> msgDto = new MsgDto<>();
        InviteWxworkGroupDto inviteWxworkGroupDto = new InviteWxworkGroupDto();
        inviteWxworkGroupDto.setGroupId(esWorkWxGroupInfo.getGroupId());
        inviteWxworkGroupDto.setArrWxids(String.join(";", wxidList));
        inviteWxworkGroupDto.setInviteType(0); //拉人进群
        msgDto.setContent(inviteWxworkGroupDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupInviteDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.INVITE_TO_GROUP.getValue());

        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.inviteJoinGroup(msgDto);
        logger.info("--调用企业微信邀请入群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量邀请入群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupBatchInviteDto
     * @return null
     */
    public void batchInviteWxWorkGroup(WxWorkGroupBatchInviteDto wxWorkGroupBatchInviteDto){
        //微信群id列表
        List<String> idList = wxWorkGroupBatchInviteDto.getIdList();
        //入群微信id列表
        List<String> memberIdList = wxWorkGroupBatchInviteDto.getMemberIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(memberIdList == null || memberIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量入群人员");
        }

        if(memberIdList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员必须少于40个");
        }

        for(String id  : idList){
            try {
                WxWorkGroupInviteDto wxWorkGroupInviteDto = new WxWorkGroupInviteDto();
                BeanUtils.copyProperties(wxWorkGroupBatchInviteDto, wxWorkGroupInviteDto);
                wxWorkGroupInviteDto.setMerId(wxWorkGroupBatchInviteDto.getMerId());
                wxWorkGroupInviteDto.setId(id);
                wxWorkGroupInviteDto.setMemberIdList(wxWorkGroupBatchInviteDto.getMemberIdList());
                inviteWxWorkGroup(wxWorkGroupInviteDto);
            }catch (Exception e){
                logger.error("--批量入群错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 查询群二维码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupQrcodeDto
     * @return null
     */
    public WxWorkGroupQrcodeVo findQrcode(WxWorkGroupQrcodeDto wxWorkGroupQrcodeDto){
        WxWorkGroupQrcodeVo wxWorkGroupQrcodeVo = new WxWorkGroupQrcodeVo();
        if(StringUtils.isBlank(wxWorkGroupQrcodeDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        String wxWorkGroupQrcodeKey = String.format(RedisCacheKeyEnum.WXWORK_GROUP_QRCODE.getKey(), wxWorkGroupQrcodeDto.getId());

        Object object = redisTemplate.opsForValue().get(wxWorkGroupQrcodeKey);
        if(object != null){
            wxWorkGroupQrcodeVo.setQrcode(object.toString());
        }

        return wxWorkGroupQrcodeVo;
    }

    /**
     * 申请群二维码
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupQrcodeDto
     * @return null
     */
    public void applyQrcode(WxWorkGroupQrcodeDto wxWorkGroupQrcodeDto){
        if(StringUtils.isBlank(wxWorkGroupQrcodeDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupQrcodeDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupQrcodeDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupQrcodeDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //申请群二维码
        MsgDto<WorkWxGetGroupQrCode> msgDto = new MsgDto<>();
        WorkWxGetGroupQrCode wxGetGroupQrCode = new WorkWxGetGroupQrCode();
        wxGetGroupQrCode.setGroupId(esWorkWxGroupInfo.getGroupId());
        msgDto.setContent(wxGetGroupQrCode);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupQrcodeDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_QRCODE.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxGetGroupQrcode(msgDto);
        logger.info("--调用申请群二维码接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 发送群公告
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupSendNoticeDto
     * @return null
     */
    public void sendNotice(WxWorkGroupSendNoticeDto wxWorkGroupSendNoticeDto){
        if(StringUtils.isBlank(wxWorkGroupSendNoticeDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxWorkGroupSendNoticeDto.getNotice())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群公告");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupSendNoticeDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupSendNoticeDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupSendNoticeDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用发送群公告接口
        MsgDto<SendGroupNoticeDto> msgDto = new MsgDto<>();
        SendGroupNoticeDto sendGroupNoticeDto = new SendGroupNoticeDto();
        sendGroupNoticeDto.setGroupId(esWorkWxGroupInfo.getGroupId());
        sendGroupNoticeDto.setContent(wxWorkGroupSendNoticeDto.getNotice());
        msgDto.setContent(sendGroupNoticeDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupSendNoticeDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_GROUP_NOTICE.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.sendGroupNotice(msgDto);
        logger.info("--调用发送群公告接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量发送群公告
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupBatchSendNoticeDto
     * @return null
     */
    public void batchSendNotice(WxWorkGroupBatchSendNoticeDto wxWorkGroupBatchSendNoticeDto){
        //微信群id列表
        List<String> idList = wxWorkGroupBatchSendNoticeDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(Strings.isBlank(wxWorkGroupBatchSendNoticeDto.getNotice())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入公告信息");
        }

        for(String id  : idList){
            try {
                WxWorkGroupSendNoticeDto wxWorkGroupSendNoticeDto = new WxWorkGroupSendNoticeDto();
                BeanUtils.copyProperties(wxWorkGroupBatchSendNoticeDto, wxWorkGroupSendNoticeDto);
                wxWorkGroupSendNoticeDto.setMerId(wxWorkGroupBatchSendNoticeDto.getMerId());
                wxWorkGroupSendNoticeDto.setId(id);
                wxWorkGroupSendNoticeDto.setNotice(wxWorkGroupBatchSendNoticeDto.getNotice());
                sendNotice(wxWorkGroupSendNoticeDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 查询群管功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public WxqWorkGroupManagerFuncVo findManagerFunc(WxWorkGroupIdDto wxWorkGroupIdDto){
        if(StringUtils.isBlank(wxWorkGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }
        WxqWorkGroupManagerFuncVo wxqWorkGroupManagerFuncVo = new WxqWorkGroupManagerFuncVo();
        WxqWorkGroupManagerFunc wxqWorkGroupManagerFunc = wxqWorkGroupManagerFuncMapper.selectByGroupId(wxWorkGroupIdDto.getId());
        if(wxqWorkGroupManagerFunc != null){
            BeanUtils.copyProperties(wxqWorkGroupManagerFunc, wxqWorkGroupManagerFuncVo);
        }

        return wxqWorkGroupManagerFuncVo;

    }

    /**
     * 设置群管功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupSetManagerFuncDto
     * @return null
     */
    public void setManagerFunc(WxWorkGroupSetManagerFuncDto wxWorkGroupSetManagerFuncDto){
        if(StringUtils.isBlank(wxWorkGroupSetManagerFuncDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupSetManagerFuncDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupSetManagerFuncDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupSetManagerFuncDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        int now = DateUtil.getNowTime();

        //查询该群的群管功能是否存在,如果存在则修改，不存在就添加
        WxqWorkGroupManagerFunc wxqWorkGroupManagerFunc = wxqWorkGroupManagerFuncMapper.selectByGroupId(wxWorkGroupSetManagerFuncDto.getId());
        if(wxqWorkGroupManagerFunc == null){ //新增
            wxqWorkGroupManagerFunc = new WxqWorkGroupManagerFunc();
            wxqWorkGroupManagerFunc.setId(IdWorker.getId());
            wxqWorkGroupManagerFunc.setMerId(wxWorkGroupSetManagerFuncDto.getMerId());
            wxqWorkGroupManagerFunc.setGroupId(wxWorkGroupSetManagerFuncDto.getId());
            wxqWorkGroupManagerFunc.setGroupWxid(esWorkWxGroupInfo.getGroupId());
            wxqWorkGroupManagerFunc.setDeviceUniqueId(esWorkWxGroupInfo.getDeviceUniqueId());
            wxqWorkGroupManagerFunc.setDeviceId(esWorkWxGroupInfo.getDeviceId());
            wxqWorkGroupManagerFunc.setGroupInviteConfrom(wxWorkGroupSetManagerFuncDto.getGroupInviteConfrom());
            wxqWorkGroupManagerFunc.setDisableGroupEditName(wxWorkGroupSetManagerFuncDto.getDisableGroupEditName());
            wxqWorkGroupManagerFunc.setCreateTime(now);
            wxqWorkGroupManagerFunc.setUpdateTime(now);
            wxqWorkGroupManagerFuncMapper.insertSelective(wxqWorkGroupManagerFunc);
        }else{//修改
            wxqWorkGroupManagerFunc.setGroupInviteConfrom(wxWorkGroupSetManagerFuncDto.getGroupInviteConfrom());
            wxqWorkGroupManagerFunc.setDisableGroupEditName(wxWorkGroupSetManagerFuncDto.getDisableGroupEditName());
            wxqWorkGroupManagerFunc.setUpdateTime(now);
            wxqWorkGroupManagerFuncMapper.updateByIdSelective(wxqWorkGroupManagerFunc);
        }

        //调用微服务发送邀请确认接口
        MsgDto<WorkWxSetGroupInviteConfirm> msgDto_inviteConfirm = new MsgDto<>();
        WorkWxSetGroupInviteConfirm  workWxSetGroupInviteConfirm = new WorkWxSetGroupInviteConfirm();
        workWxSetGroupInviteConfirm.setGroupId(esWorkWxGroupInfo.getGroupId());
        workWxSetGroupInviteConfirm.setStatus(wxWorkGroupSetManagerFuncDto.getGroupInviteConfrom());
        msgDto_inviteConfirm.setContent(workWxSetGroupInviteConfirm);
        msgDto_inviteConfirm.setId(IdWorker.getId());
        msgDto_inviteConfirm.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto_inviteConfirm.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto_inviteConfirm.setMerId(deviceWxworkInfo.getMerId());
        msgDto_inviteConfirm.setMsgType(MessageFuncEnum.SET_GROUP_INVITE_CONFIRM.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo_inviteConfirm = uzaiImClientFeignService.workwxSetgroupInviteconfirm(msgDto_inviteConfirm);
        logger.info("--调用企业微信发送邀请确认接口--para={},result={}",JSONObject.toJSONString(msgDto_inviteConfirm), JSONObject.toJSONString(uzaiRespVo_inviteConfirm));
        if(uzaiRespVo_inviteConfirm != null && uzaiRespVo_inviteConfirm.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo_inviteConfirm.getMsg());
        }

        //调用微服务发送禁止修改群名接口
        MsgDto<WorkWxProhibitSetGroupName> msgDto_prohibitSetGroupName = new MsgDto<>();
        WorkWxProhibitSetGroupName  workWxProhibitSetGroupName = new WorkWxProhibitSetGroupName();
        workWxProhibitSetGroupName.setGroupId(esWorkWxGroupInfo.getGroupId());
        workWxProhibitSetGroupName.setStatus(wxWorkGroupSetManagerFuncDto.getDisableGroupEditName());
        msgDto_prohibitSetGroupName.setContent(workWxProhibitSetGroupName);
        msgDto_prohibitSetGroupName.setId(IdWorker.getId());
        msgDto_prohibitSetGroupName.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto_prohibitSetGroupName.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto_prohibitSetGroupName.setMerId(deviceWxworkInfo.getMerId());
        msgDto_prohibitSetGroupName.setMsgType(MessageFuncEnum.PROHIBIT_SET_GROUPNAME.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo_prohibitSetGroupName = uzaiImClientFeignService.workwxProhibitSetgroupname(msgDto_prohibitSetGroupName);
        logger.info("--调用企业微信发送禁止修改群名接口--para={},result={}",JSONObject.toJSONString(msgDto_prohibitSetGroupName), JSONObject.toJSONString(uzaiRespVo_prohibitSetGroupName));
        if(uzaiRespVo_prohibitSetGroupName != null && uzaiRespVo_prohibitSetGroupName.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo_prohibitSetGroupName.getMsg());
        }
    }

    /**
     * 批量设置群管功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupBatchSetManagerFuncDto
     * @return null
     */
    public void batchSetManagerFunc(WxWorkGroupBatchSetManagerFuncDto wxWorkGroupBatchSetManagerFuncDto){
        //微信群id列表
        List<String> idList = wxWorkGroupBatchSetManagerFuncDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        for(String id  : idList){
            try {
                WxWorkGroupSetManagerFuncDto wxWorkGroupSetManagerFuncDto = new WxWorkGroupSetManagerFuncDto();
                BeanUtils.copyProperties(wxWorkGroupBatchSetManagerFuncDto, wxWorkGroupSetManagerFuncDto);
                wxWorkGroupSetManagerFuncDto.setMerId(wxWorkGroupBatchSetManagerFuncDto.getMerId());
                wxWorkGroupSetManagerFuncDto.setId(id);
                wxWorkGroupSetManagerFuncDto.setGroupInviteConfrom(wxWorkGroupBatchSetManagerFuncDto.getGroupInviteConfrom());
                wxWorkGroupSetManagerFuncDto.setDisableGroupEditName(wxWorkGroupBatchSetManagerFuncDto.getDisableGroupEditName());
                setManagerFunc(wxWorkGroupSetManagerFuncDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 解散本群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public void deleteWxWorkGroup(WxWorkGroupIdDto wxWorkGroupIdDto){
        if(StringUtils.isBlank(wxWorkGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupIdDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用解散本群接口
        MsgDto<WorkWxDismissGroup> msgDto = new MsgDto<>();
        WorkWxDismissGroup workWxDismissGroup = new WorkWxDismissGroup();
        workWxDismissGroup.setGroupId(esWorkWxGroupInfo.getGroupId());
        msgDto.setContent(workWxDismissGroup);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupIdDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.DISMISS_GROUP.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxDismissGroup(msgDto);
        logger.info("--调用解散本群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 退出本群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public void quiteWxWorkGroup(WxWorkGroupIdDto wxWorkGroupIdDto){
        if(StringUtils.isBlank(wxWorkGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupIdDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //发送退群指令MQ消息
        MsgDto<QuitGroupDto> msgDto = new MsgDto<>();
        QuitGroupDto quitGroupDto = new QuitGroupDto();
        quitGroupDto.setGroupId(esWorkWxGroupInfo.getGroupId());
        msgDto.setContent(quitGroupDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupIdDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.QUIT_GROUP.getValue());
        noticeMsgPushProducerService.quitWxGroup(msgDto);

        logger.info("--发送退群指令MQ消息--para={}",JSONObject.toJSONString(msgDto));
    }

    /**
     * 刷新成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupIdDto
     * @return null
     */
    public void refreshMember(WxWorkGroupIdDto wxWorkGroupIdDto){
        if(StringUtils.isBlank(wxWorkGroupIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupIdDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupIdDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupIdDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //发送刷新成员列表指令MQ消息
        MsgDto<GetGroupMemberListDto> msgDto = new MsgDto<>();
        GetGroupMemberListDto getGroupMemberListDto = new GetGroupMemberListDto();
        getGroupMemberListDto.setGroupId(esWorkWxGroupInfo.getGroupId());
        msgDto.setContent(getGroupMemberListDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupIdDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_MEMBER_LIST.getValue());
        noticeMsgPushProducerService.getGroupMemberList(msgDto);
        logger.info("--发送刷新成员MQ消息--para={}",JSONObject.toJSONString(msgDto));
    }

    /**
     * 查询欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkGroupWelcomeFindListDto
     * @return null
     */
    public List<WxWorkGroupWelcomeVo> findWelcomeList(WxqWorkGroupWelcomeFindListDto wxqWorkGroupWelcomeFindListDto){

        List<WxWorkGroupWelcomeVo> wxWorkGroupWelcomeVoList = new ArrayList<>();

        if(wxqWorkGroupWelcomeFindListDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqWorkGroupWelcomeFindListDto.getDeviceUniqueId(), wxqWorkGroupWelcomeFindListDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        WxqWorkGroupWelcomeQuery query = new WxqWorkGroupWelcomeQuery();
        query.setMerId(wxqWorkGroupWelcomeFindListDto.getMerId());
        query.setDeviceUniqueId(deviceWxworkInfo.getId());
        List<WxqWorkGroupWelcome> wxqWorkGroupWelcomeList = wxqWorkGroupWelcomeMapper.findByList(query);
        if(wxqWorkGroupWelcomeList != null && wxqWorkGroupWelcomeList.size() > 0){
            for (WxqWorkGroupWelcome wxqWorkGroupWelcome : wxqWorkGroupWelcomeList) {
                WxWorkGroupWelcomeVo wxWorkGroupWelcomeVo = new WxWorkGroupWelcomeVo();
                BeanUtils.copyProperties(wxqWorkGroupWelcome, wxWorkGroupWelcomeVo);
                wxWorkGroupWelcomeVoList.add(wxWorkGroupWelcomeVo);
            }
        }

        return wxWorkGroupWelcomeVoList;
    }

    /**
     * 获取欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkGroupWelcomeRefleshDto
     * @return null
     */
    public void refreshWelcome(WxqWorkGroupWelcomeRefleshDto wxqWorkGroupWelcomeRefleshDto){

        if(wxqWorkGroupWelcomeRefleshDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqWorkGroupWelcomeRefleshDto.getDeviceUniqueId(), wxqWorkGroupWelcomeRefleshDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用微服务同步欢迎语
        MsgDto<WorkWxGetGroupWelcomeMsgList> msgDto = new MsgDto<>();
        WorkWxGetGroupWelcomeMsgList wxGetGroupWelcomeMsgList = new WorkWxGetGroupWelcomeMsgList();
        wxGetGroupWelcomeMsgList.setLimit(100); //一页查询100条
        wxGetGroupWelcomeMsgList.setType(10);
        wxGetGroupWelcomeMsgList.setOffset("");
        msgDto.setContent(wxGetGroupWelcomeMsgList);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxqWorkGroupWelcomeRefleshDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_GROUP_WELCOMEMSG_LIST.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxGetGroupWelcomemsgList(msgDto);
        logger.info("--调用获取欢迎语接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 设置欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupWelcomeSetDto
     * @return null
     */
    public void setWelcome(WxWorkGroupWelcomeSetDto wxWorkGroupWelcomeSetDto){
        if(StringUtils.isBlank(wxWorkGroupWelcomeSetDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupWelcomeSetDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupWelcomeSetDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupWelcomeSetDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        if(wxWorkGroupWelcomeSetDto.getWelcomeId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入欢迎语id");
        }

        WxqWorkGroupWelcome wxqWorkGroupWelcome = wxqWorkGroupWelcomeMapper.selectById(wxWorkGroupWelcomeSetDto.getWelcomeId());
        if(wxqWorkGroupWelcome == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "欢迎语不存在");
        }

        //调用微服务设置欢迎语接口
        MsgDto<WorkWxSetGroupWelcomeMsg> msgDto = new MsgDto<>();
        WorkWxSetGroupWelcomeMsg workWxSetGroupWelcomeMsg = new WorkWxSetGroupWelcomeMsg();
        workWxSetGroupWelcomeMsg.setGroupId(esWorkWxGroupInfo.getGroupId());
        workWxSetGroupWelcomeMsg.setMsgIndex(wxqWorkGroupWelcome.getMsgId());
        workWxSetGroupWelcomeMsg.setMsgType(wxqWorkGroupWelcome.getMsgType());
        msgDto.setContent(workWxSetGroupWelcomeMsg);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupWelcomeSetDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SET_GROUP_WELCOMEMSG.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetgroupWelcomemsg(msgDto);
        logger.info("--调用设置欢迎语接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量设置欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupWelcomeBatchSetDto
     * @return null
     */
    public void batchSetWelcome(WxWorkGroupWelcomeBatchSetDto wxWorkGroupWelcomeBatchSetDto){
        //微信群id列表
        List<String> idList = wxWorkGroupWelcomeBatchSetDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(wxWorkGroupWelcomeBatchSetDto.getWelcomeId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入欢迎语id");
        }
        for(String id  : idList){
            try {
                WxWorkGroupWelcomeSetDto wxWorkGroupWelcomeSetDto = new WxWorkGroupWelcomeSetDto();
                BeanUtils.copyProperties(wxWorkGroupWelcomeBatchSetDto, wxWorkGroupWelcomeSetDto);
                wxWorkGroupWelcomeSetDto.setMerId(wxWorkGroupWelcomeBatchSetDto.getMerId());
                wxWorkGroupWelcomeSetDto.setId(id);
                wxWorkGroupWelcomeSetDto.setWelcomeId(wxWorkGroupWelcomeBatchSetDto.getWelcomeId());
                setWelcome(wxWorkGroupWelcomeSetDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 添加欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupWelcomeAddDto
     * @return null
     */
    public void addWelcome(WxWorkGroupWelcomeAddDto wxWorkGroupWelcomeAddDto){

        if(StringUtils.isBlank(wxWorkGroupWelcomeAddDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupWelcomeAddDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupWelcomeAddDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        if(wxWorkGroupWelcomeAddDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxWorkGroupWelcomeAddDto.getDeviceUniqueId(), wxWorkGroupWelcomeAddDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        if(StringUtils.isBlank(wxWorkGroupWelcomeAddDto.getMsg())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入欢迎语");
        }

        //调用微服务设置欢迎语接口
        MsgDto<WorkWxAddGroupWelcomeMsg> msgDto = new MsgDto<>();
        WorkWxAddGroupWelcomeMsg workWxAddGroupWelcomeMsg = new WorkWxAddGroupWelcomeMsg();
        workWxAddGroupWelcomeMsg.setContent(wxWorkGroupWelcomeAddDto.getMsg());
        workWxAddGroupWelcomeMsg.setType(1); //添加并设置
        workWxAddGroupWelcomeMsg.setArrGroupId(esWorkWxGroupInfo.getGroupId()); //单个群微信id
        msgDto.setContent(workWxAddGroupWelcomeMsg);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupWelcomeAddDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.ADD_GROUP_WELCOMEMSG.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxAddgroupWelcomemsg(msgDto);
        logger.info("--调用添加欢迎语接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 批量添加欢迎语
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupWelcomeBatchAddDto
     * @return null
     */
    public void batchAddWelcome(WxWorkGroupWelcomeBatchAddDto wxWorkGroupWelcomeBatchAddDto){
        List<String> idList = wxWorkGroupWelcomeBatchAddDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择群");
        }

        //群列表
        List<String> groupIdList = new ArrayList<>();
        for (String id : idList) {
            //查询
            String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupWelcomeBatchAddDto.getMerId());
            //查询微信群
            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, id, null);
            EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
            if(esWorkWxGroupInfo == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
            }
            groupIdList.add(esWorkWxGroupInfo.getGroupId());
        }

        if(wxWorkGroupWelcomeBatchAddDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxWorkGroupWelcomeBatchAddDto.getDeviceUniqueId(), wxWorkGroupWelcomeBatchAddDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        if(StringUtils.isBlank(wxWorkGroupWelcomeBatchAddDto.getMsg())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入欢迎语");
        }

        //调用微服务设置欢迎语接口
        MsgDto<WorkWxAddGroupWelcomeMsg> msgDto = new MsgDto<>();
        WorkWxAddGroupWelcomeMsg workWxAddGroupWelcomeMsg = new WorkWxAddGroupWelcomeMsg();
        workWxAddGroupWelcomeMsg.setContent(wxWorkGroupWelcomeBatchAddDto.getMsg());
        workWxAddGroupWelcomeMsg.setType(1); //添加并设置
        workWxAddGroupWelcomeMsg.setArrGroupId(String.join(";", groupIdList)); //多个群微信id以分号隔开
        msgDto.setContent(workWxAddGroupWelcomeMsg);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupWelcomeBatchAddDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.ADD_GROUP_WELCOMEMSG.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxAddgroupWelcomemsg(msgDto);
        logger.info("--调用添加欢迎语接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 查询防骚扰规则
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkGroupRuleFindListDto
     * @return null
     */
    public List<WxWorkGroupRuleVo> findRuleList(WxqWorkGroupRuleFindListDto wxqWorkGroupRuleFindListDto){

        List<WxWorkGroupRuleVo> wxWorkGroupRuleVoList = new ArrayList<>();

        if(wxqWorkGroupRuleFindListDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqWorkGroupRuleFindListDto.getDeviceUniqueId(), wxqWorkGroupRuleFindListDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        WxqWorkGroupRuleQuery query = new WxqWorkGroupRuleQuery();
        query.setMerId(wxqWorkGroupRuleFindListDto.getMerId());
        query.setDeviceUniqueId(deviceWxworkInfo.getId());
        List<WxqWorkGroupRule> wxqWorkGroupRuleList = wxqWorkGroupRuleMapper.findByList(query);
        if(wxqWorkGroupRuleList != null && wxqWorkGroupRuleList.size() > 0){
            for (WxqWorkGroupRule wxqWorkGroupRule : wxqWorkGroupRuleList) {
                WxWorkGroupRuleVo wxWorkGroupRuleVo = new WxWorkGroupRuleVo();
                BeanUtils.copyProperties(wxqWorkGroupRule, wxWorkGroupRuleVo);
                wxWorkGroupRuleVoList.add(wxWorkGroupRuleVo);
            }
        }
        return wxWorkGroupRuleVoList;
    }

    /**
     * 获取防骚扰规则
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqWorkGroupRuleRefleshDto
     * @return null
     */
    public void refreshRule(WxqWorkGroupRuleRefleshDto wxqWorkGroupRuleRefleshDto){

        if(wxqWorkGroupRuleRefleshDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(wxqWorkGroupRuleRefleshDto.getDeviceUniqueId(), wxqWorkGroupRuleRefleshDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //调用微服务获取防骚扰规则
        MsgDto<Object> msgDto = new MsgDto<>();
        msgDto.setContent(null);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxqWorkGroupRuleRefleshDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_ANTISPAM_RULE_LIST.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxGetAntispamrule(msgDto);
        logger.info("--调用获取欢迎语接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 设置防骚扰规则
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupRuleSetDto
     * @return null
     */
    public void setRule(WxWorkGroupRuleSetDto wxWorkGroupRuleSetDto){
        if(StringUtils.isBlank(wxWorkGroupRuleSetDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupRuleSetDto.getMerId());
        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupRuleSetDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(esWorkWxGroupInfo.getDeviceUniqueId(), wxWorkGroupRuleSetDto.getMerId());
        if(deviceWxworkInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        if(wxWorkGroupRuleSetDto.getRuleIdList() == null || wxWorkGroupRuleSetDto.getRuleIdList().size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择防骚扰规则");
        }

        //查询数据库当中的规则
        List<String> ruleIdList = new ArrayList<>();
        for (Long id : wxWorkGroupRuleSetDto.getRuleIdList()) {
            WxqWorkGroupRule wxqWorkGroupRule = wxqWorkGroupRuleMapper.selectById(id);
            if(wxqWorkGroupRule != null){
                ruleIdList.add(wxqWorkGroupRule.getRuleId());
            }
        }

        //调用微服务设置防骚扰规则接口
        MsgDto<WorkWxSetAntiSpamRule> msgDto = new MsgDto<>();
        WorkWxSetAntiSpamRule workWxSetAntiSpamRule = new WorkWxSetAntiSpamRule();
        workWxSetAntiSpamRule.setGroupId(esWorkWxGroupInfo.getGroupId());
        workWxSetAntiSpamRule.setRuleList(String.join(";", ruleIdList));
        msgDto.setContent(workWxSetAntiSpamRule);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(wxWorkGroupRuleSetDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SET_ANTISPAM_RULE.getValue());
        //调用微服务
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetAntispamrule(msgDto);
        logger.info("--调用设置防骚扰规则接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }


    /**
     * 批量设置防骚扰规则
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxWorkGroupRuleBatchSetDto
     * @return null
     */
    public void batchSetRule(WxWorkGroupRuleBatchSetDto wxWorkGroupRuleBatchSetDto){
        //微信群id列表
        List<String> idList = wxWorkGroupRuleBatchSetDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        if(wxWorkGroupRuleBatchSetDto.getRuleIdList() == null || wxWorkGroupRuleBatchSetDto.getRuleIdList().size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择防骚扰规则");
        }
        for(String id  : idList){
            try {
                WxWorkGroupRuleSetDto wxWorkGroupRuleSetDto = new WxWorkGroupRuleSetDto();
                BeanUtils.copyProperties(wxWorkGroupRuleBatchSetDto, wxWorkGroupRuleSetDto);
                wxWorkGroupRuleSetDto.setMerId(wxWorkGroupRuleBatchSetDto.getMerId());
                wxWorkGroupRuleSetDto.setId(id);
                wxWorkGroupRuleSetDto.setRuleIdList(wxWorkGroupRuleBatchSetDto.getRuleIdList());
                setRule(wxWorkGroupRuleSetDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 企业微信批量踢出群成员
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param batchKickWxWorkGroupMemberDto
     * @return null
     */
    public void batchKickWxWorkGroupMember(BatchKickWxWorkGroupMemberDto batchKickWxWorkGroupMemberDto){
        //微信群id列表
        List<String> idList = batchKickWxWorkGroupMemberDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择批量操作的微信群");
        }

        List<String> wxidList = batchKickWxWorkGroupMemberDto.getWxidList();

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(wxidList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        for(String id  : idList){
            try {
                WxWorkGroupMemberKickDto wxWorkGroupMemberKickDto = new WxWorkGroupMemberKickDto();
                BeanUtils.copyProperties(batchKickWxWorkGroupMemberDto, wxWorkGroupMemberKickDto);
                wxWorkGroupMemberKickDto.setMerId(batchKickWxWorkGroupMemberDto.getMerId());
                wxWorkGroupMemberKickDto.setGroupId(id);
                wxWorkGroupMemberKickDto.setQuitReason(batchKickWxWorkGroupMemberDto.getQuitReason());
                wxWorkGroupMemberService.kickWxWorkGroupMember(wxWorkGroupMemberKickDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }
    }

    /**
     * 删除单个机器人的通讯录
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public void deleteWxWorkGroupByDeviceUniqueId(Long deviceUniqueId, Long merId){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", merId));
        //机器人唯一id
        boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
        searchSourceBuilder_del.query(boolQuery_and).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_workwx_contacts = EsIndexName.UZAI_WORKWX_GROUP_INFO;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_workwx_contacts, deleteByQueryRequest);
    }

    /**
     * 修改企业微信群备注
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxWorkGroupUpdateRemarkDto
     * @return null
     */
    public void updateRemark(WxWorkGroupUpdateRemarkDto wxWorkGroupUpdateRemarkDto){
        if(StringUtils.isBlank(wxWorkGroupUpdateRemarkDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxWorkGroupUpdateRemarkDto.getMerId());

        //查询微信群
        Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, wxWorkGroupUpdateRemarkDto.getId(), null);
        EsWorkWxGroupInfo esWorkWxGroupInfo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWorkWxGroupInfo.class);
        if(esWorkWxGroupInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群不存在");
        }

        //修改通讯录群备注
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("remark", wxWorkGroupUpdateRemarkDto.getRemark());
        elasticsearchUtilGroupMsg.updateDataNullById(jsonObject, uzai_workwx_group_info, wxWorkGroupUpdateRemarkDto.getId());

        //延迟1秒
        try {
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    @Override
    public void batchAddManager(BatchAddManagerDto batchAddManagerDto) {
        if(batchAddManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(batchAddManagerDto.getIdList()==null||batchAddManagerDto.getIdList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(batchAddManagerDto.getWxidList()==null||batchAddManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(batchAddManagerDto.getWxidList().size()>3){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多设置3个管理员");
        }
        for(String id  : batchAddManagerDto.getIdList()){
            try {
                List<String> WxIdList = new ArrayList<>();
                for (String wxId : batchAddManagerDto.getWxidList()) {
                    int startIndex = id.indexOf("R:");
                    int endIndex = id.indexOf("_", startIndex);
                    if (endIndex == -1) {
                        endIndex = id.length();
                    }
                    String groupId = id.substring(startIndex, endIndex);
                    StringBuilder stringBuffer = new StringBuilder();
                    stringBuffer.append(batchAddManagerDto.getMerId());
                    stringBuffer.append("_");
                    stringBuffer.append(groupId);
                    stringBuffer.append("_");
                    stringBuffer.append(wxId);
                    WxIdList.add(stringBuffer.toString());
                }

                AddManagerDto addManagerDto = new AddManagerDto();
                addManagerDto.setMerId(batchAddManagerDto.getMerId());
                addManagerDto.setGroupId(id);
                addManagerDto.setWxidList(WxIdList);
                wxWorkGroupMemberService.addManager(addManagerDto);
            }catch (Exception e){
                logger.error("--批量操作错误，err={}",e.getMessage());
            }
        }

    }
}
